<!--
 * @Author: lemon 719771893@qq.com
 * @Date: 2025-03-01 20:44:47
 * @LastEditors: 李梦
 * @LastEditTime: 2025-03-06 10:16:04
 * @FilePath: /ranyu_anchor_new/src/views/register/components/PayMethod.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="approval-content">
    <p style="font-size: 16px">
      “根据《电子商务法》、《网络交易监督管理办法》、《消费者权益保护法》等国家监管法规，RANYU官方有权监管、审核、监测您的直播内容与质量，保护消费者权益不受侵害。请在本页面完成创作者质量保证金缴纳”
    </p>
    <div class="tip" @click="displayModalBtn">常见保证金问题</div>

    <template v-if="props.step == 4">
      <div class="remind-box">
        <div class="remind">
          <div class="remind-top">
            <span style="color: #4e5969">您需缴纳的保证金金额为:</span>
            <span style="color: #000000; font-weight: bold; font-size: 24px">￥500.00</span>
          </div>
          <div class="remind-bottom">保证金金额解释:此金额根据您的直播类目和平台规则制定</div>
        </div>
      </div>
      <div class="tip-box">
        <div v-show="!checked" class="tip">
          <span class="circle">!</span>
          <span style="color: #777575; font-size: 10px">请勾选当前协议</span>
        </div>
      </div>
      <div class="check">
        <el-checkbox v-model="checked" label="" size="large" @change="handleSelect" />
        <span style="font-size: 14px">
          请勾选并同意
          <span href="#" style="color: #165dff; cursor: default" @click="protocolVisible = true">
            《创作者质量保证金协议》
          </span>
        </span>
      </div>
    </template>
  </div>
  <div class="footer">
    <template v-if="props.step == 4">
      <div class="footer-title">请选择支付方式</div>
      <div class="footer-box">
        <div class="item" @click="handlePay('ALI_NATIVE')">
          <img src="@/assets/pay/zfb.png" alt="#" class="icon" />
          <span class="text">支付宝</span>
        </div>
        <div class="item" @click="handlePay('WECHAT_NATIVE')">
          <img src="@/assets/pay/wx.png" alt="#" class="icon" />
          <span class="text">微信</span>
        </div>
      </div>
    </template>
    <!-- 支付二维码弹窗 -->
    <el-dialog v-model="codeVisible" width="380" :before-close="handleClose" align-center>
      <div style="text-align: center; font-weight: bold" class="m-b-4">
        {{ status == 1 ? "创作者质量保证金缴纳二维码" : "保证金缴纳成功！" }}
      </div>
      <template v-if="status == 1">
        <div class="code-box">
          <qr-code-vue :value="codeUrl" size="200px"></qr-code-vue>
        </div>
        <div style="text-align: center">请用扫码软件进行扫码支付</div>
      </template>
      <template v-else>
        <div class="success-box">
          <img src="@/assets/register/pay-success.svg" width="48" height="48" />
          <span class="price">￥500.00</span>
        </div>
        <div class="m-t-5">
          <p>缴纳时间:{{ formatDate(time, "Y-M-D h:m:s") }}</p>
          <p>缴纳明细:创作者质量保证金</p>
          <p>
            保证金查看:
            <span style="color: #3d3d3d">主播云工作台-主播信息-创作者质量保证金</span>
          </p>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="toFirstPage">加入</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 常见保证金问题 弹窗 -->
  <el-dialog v-model="questionVisible" width="400" style="height: 500px">
    <template #header>
      <div style="text-align: center">常见保证金问题</div>
    </template>
    <div>
      <span>1、支付失败怎么办?</span>
      <p>
        首先，请检查支付账户的余额是否充足，支付密码是否正确，网络是否正常等自身因素若这些都没问题，查看支付页面的提示信息，根据提示进行操作。如可能需要更新支付软件、更换支付方式等。如果仍然无法解决，联系支付平台的客服或相关金融机构了解具体原因，并按照他们的指导进行处理。
      </p>

      <span>2、如何查看保证金缴纳记录?</span>
      <p>
        你可以查看平台的站内消息中心、手机短信或电子邮箱，找到与保证金缴纳相关的通知，这些通知中可能会包含保证金缴纳的基本信息，也可以作为查看缴纳记录的辅助依据。
      </p>

      <span>3、保证金是否可以退还?</span>
      <p>
        可以退还，需要满足以下退还条件： 注册成为主播时长≥3个自然月; 在播期间违规被封禁次数3次;
        在播期间违规被警告次数&lt;10次; 未发生经核实确实存在的违反《创作者质量保证金》协议的行为。
      </p>
    </div>
  </el-dialog>
  <!-- 协议弹窗 -->
  <el-dialog
    v-model="protocolVisible"
    style="
      width: 50%;
      height: 60vh;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    "
  >
    <div class="docx-style" @scroll="handleScroll">
      <vue-office-docx :src="protocolSrc" @error="errorHandler" />
    </div>
    <div class="btn-box">
      <el-button type="primary" :disabled="isRead" @click="handleAccepted">接受并同意</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "PayMethod",
};
</script>
<script lang="ts" setup>
//引入VueOfficeDocx组件相关
import VueOfficeDocx from "@vue-office/docx";
import QrCodeVue from "vue-qrcode";
import { ref, inject } from "vue";
import AuthAPI from "@/api/auth";
import router from "@/router";
import { formatDate } from "@/utils/index";

const { getInfo } = inject("getInfo");
const props = defineProps({
  step: {
    type: Number,
    default: 4,
  },
});
const codeUrl = ref("");
const codeVisible = ref(false); // 二维码弹窗显示/隐藏

const protocolVisible = ref(false); // 协议弹窗
const protocolSrc = ref(
  "https://static.ranyu.vip/2025/index/pdf/anchor/%E3%80%8A%E5%88%9B%E4%BD%9C%E8%80%85%E8%B4%A8%E9%87%8F%E4%BF%9D%E8%AF%81%E9%87%91%E7%BC%B4%E7%BA%B3%E5%8D%8F%E8%AE%AE%E3%80%8B.docx"
); // 协议地址
const questionVisible = ref(false); // 常见问题弹窗
const status = ref(1); // 1未支付，2支付成功
const time = ref(""); // 保证金缴纳时间

// 展示保证金常见问题框
const displayModalBtn = () => {
  questionVisible.value = true;
};

const errorHandler = () => {
  console.log("协议加载失败");
};

const checked = ref(false);
const isRead = ref(true);
// 监听滚动
const handleScroll = (e: any) => {
  const div = e.target;
  const { scrollTop, clientHeight, scrollHeight } = div;

  // 判断是否滚动到底部
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    isRead.value = false;
  }
};

const handleAccepted = () => {
  checked.value = true;
  protocolVisible.value = false;
};

const handleSelect = (value: Boolean) => {
  if (!value) return;
  checked.value = false;
  protocolVisible.value = true;
};
let pollingTimer: number | null = null; // 全局定时器变量

const getCode = async (type: string) => {
  try {
    const res = await AuthAPI.getPayCode({
      payType: type,
      userBizId: localStorage.getItem("userBizId") || "",
    });
    codeVisible.value = true; // 显示二维码弹窗
    codeUrl.value = res.WECHAT_NATIVE_QR_CODE || res.ALI_NATIVE_QR_CODE; // 设置二维码 URL

    // 在获取到二维码后，开始轮询支付结果
    if (!pollingTimer) {
      getResult(res.orderNo);
    }
  } catch (error) {
    console.error("获取支付二维码失败:", error);
    ElMessage({
      message: "获取支付二维码失败",
      type: "error",
    });
  }
};

// 支付
const handlePay = (type: string) => {
  if (!checked.value) {
    ElMessage({
      message: "请勾选并同意相关协议",
      type: "warning",
    });
  } else {
    getCode(type);
  }
};

// 获取支付结果
const getResult = async (no: string) => {
  try {
    // 清除之前的定时器（如果有）
    if (pollingTimer) {
      clearInterval(pollingTimer);
      pollingTimer = null;
    }

    // 开启新的定时器
    pollingTimer = setInterval(async () => {
      try {
        const res = await AuthAPI.getPayResult({ outTradeNo: no });
        // 检查支付状态
        if (res.payStatus === "AGG_PAY_SUC") {
          // 支付成功，更新状态并清除定时器
          time.value = res.payTime;
          status.value = 2;
          clearPollingTimer(); // 清除定时器
          codeVisible.value = true; // 显示结果
          setTimeout(() => {
            localStorage.setItem("userType", "3");
            router.push("/dashboard");
          }, 3000);
        } else if (res.payStatus === "AGG_PAY_WAIT") {
          // 支付等待中，继续轮询
          console.log("等待支付中...");
        } else {
          // 其他状态，清除定时器
          clearPollingTimer();
          console.log("支付状态异常:", res.payStatus);
        }
      } catch (error) {
        console.error("轮询请求失败:", error);
        clearPollingTimer(); // 发生错误时清除定时器
      }
    }, 1000); // 每 1 秒轮询一次
  } catch (error) {
    console.error("error:", error);
  }
};

// 清除定时器
const clearPollingTimer = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer);
    pollingTimer = null;
  }
};

// 关闭弹窗
const handleClose = () => {
  codeVisible.value = false; // 隐藏二维码弹窗
  clearPollingTimer(); // 清除定时器
  getInfo(); // 刷新页面获取最新状态
};
const toFirstPage = () => {
  localStorage.setItem("userType", "3");
  router.push("/dashboard");
};
</script>

<style lang="scss" scoped>
.approval-content {
  width: 65%;
  background: #ffffff;
  font-size: 14px;
  color: #4e5969;
  margin: 40px auto;
  padding: 34px 54px;
  .tip {
    user-select: none;
    cursor: pointer;
    color: #165dff;
    width: 100%;
    text-align: right;
    font-size: 10px;
  }
  .remind {
    width: 320px;
    padding: 18px 30px;
    margin: auto;
    &-top {
    }
    &-bottom {
      padding: 6px 0;
      color: #4e5969;
      font-size: 10px;
    }
  }
  .tip-box {
    padding-left: 20%;
    height: 30px;
    margin-top: 20px;
    .tip {
      width: 169px;
      padding: 4px;
      border-radius: 2px;
      background: #fdf5e8;
      box-sizing: border-box;
      border: 0.5px solid #f2c975;
      display: flex;
      align-items: center;
      .circle {
        display: inline-block;
        width: 22px;
        height: 22px;
        line-height: 22px;
        background: orange;
        margin-right: 10px;
        margin-left: 10px;
        border-radius: 50%;
        color: #ffffff;
        text-align: center;
      }
    }
  }
  .check {
    width: 100%;
    margin-top: 10px;
    display: flex;
    align-items: center;
    padding-left: 20%;
  }
}
.footer {
  width: 64%;
  margin: 0 auto;
  &-title {
    text-align: left;
    width: 100%;
    font-weight: bold;
    margin-bottom: 10px;
    color: #3d3d3d;
  }
  &-box {
    width: 100%;
    padding: 30px 0;
    display: flex;
    justify-content: center;

    .item {
      padding: 10px;
      display: inline-flex;
      flex-direction: column;
      margin-left: 100px;
      .icon {
        width: 40px;
        height: 40px;
      }
      .text {
        width: 40px;
        font-size: 12px;
        margin-top: 4px;
        text-align: center;
      }
    }
  }
  .code-box {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }
  .success-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
    .price {
      text-align: center;
      margin-top: 16px;
      font-size: 14px;
      color: #1d2129;
    }
  }
}
.loginRight {
  width: 100px;
  height: 100px;
}
.payClass {
  display: flex;
  flex-direction: column;
  align-items: center;
}
::v-deep .docx-wrapper {
  padding: 0 !important;
  background: none !important;
}
::v-deep .docx-wrapper > section.docx {
  margin-bottom: 0;
  padding: 20px 50px !important;
}
.docx-style {
  width: 100%;
  height: 48vh;
  overflow-y: scroll;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* Internet Explorer 10+ */
  background-color: #fff;
}
/* 对于 WebKit 浏览器（如 Chrome, Safari） */
.docx-style::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera*/
}
.btn-box {
  width: 100%;
  padding: 12px;
  text-align: center;
}
</style>
